<template>
    <div v-if="orderData" class="order-wrap">
        <van-nav-bar title="确认订单" left-arrow fixed @click-left="onClickLeft" />

        <div class="address-top-box">
            <!-- 无收货地址 -->
            <div v-if="isLoaded && !(orderData && orderData.address && orderData.address.address)"
                @click="handleToSelectAddress" class="no-address-box">
                <div class="address-default-text">请选择收货地址</div>
                <img class="address-arrow-icon" :src="addressArrowIcon" alt="">

                <img class="address-border-bottom" :src="addressBorderBg" alt="">
            </div>

            <!-- 有收货地址 -->
            <div v-if="isLoaded && (orderData && orderData.address && orderData.address.address)" class="default-box"
                @click="handleToSelectAddress">
                <img class="address-lation" :src="addressLationIcon" alt="">
                <div class="address-content">
                    <div class="address-content-name">
                        <div class="address-user-name">{{ orderData.address.contact.split(' ')[0] }}</div>
                        <div class="address-user-tel">{{ orderData.address.contact.split(' ')[1] }}</div>
                    </div>
                    <div class="address-content-info">{{ orderData.address.address }}</div>
                </div>
                <img class="address-arrow-icon" :src="addressArrowIcon" alt="">
                <img class="address-border-bottom" :src="addressBorderBg" alt="">
            </div>
        </div>


        <!-- 中部 -->
        <div v-for="(item, index) in orderData.items" :key="index" class="good-shop-box">
            <div class="shop-top">
                <img class="shop-top-icon" :src="orderShopIcon" alt="">
                <div class="shop-top-title">{{ item.shop_name }}</div>
            </div>
            <div v-for="(gItem, gIndex) in item.items" :key="gIndex" class="good-item">
                <img class="good-item-img" :src="gItem.left_icon" alt="">
                <div class="good-item-content">
                    <div class="good-item-content-name">{{ gItem.title }}</div>
                    <div class="good-item-content-sku">{{ gItem.sku_text }}</div>
                    <!-- 字段未出 -->
                    <!-- <div class="good-info-subsidy">
                        <div v-if="gItem.subsidy_text" class="good-info-subsidy-btn">{{ gItem.subsidy_text }}</div>
                    </div> -->
                    <div class="good-info-subsidy" v-if="gItem.labels.length">

                        <div class="good-info-subsidy-btn" :style="{ color: items.color }"
                            v-for="items, indexs in gItem.labels" :key="indexs">
                            {{ items.name }}
                        </div>
                    </div>
                    <div class="good-item-price">{{ gItem.price_text }}</div>
                </div>

                <div class="good-num-fix">x{{ gItem.quantity }}</div>
            </div>

            <!-- 备注 -->
            <div class="good-remark">
                <van-field v-model="item.user_note" rows="1" autosize label="商品备注" type="textarea"
                    placeholder="选填：填写留言" />
            </div>

            <div class="good-total">
                <div class="good-total-num">{{ item.summary_text }}，小计：</div>
                <div class="good-total-price">{{ item.summary_price_text }}</div>
            </div>

        </div>
        <div v-if="orderData.belong_status == 1">
            <div class="input-ul">
                <van-field v-model="address" readonly label-width="130px" label="选择归属区域：" :right-icon="goodCeilArrow"
                    placeholder="选择归属区域" @click="showPopup = true" />
                <div></div>
            </div>

        </div>
        <!-- <div class="youhui_title" @click="getCoupon" v-if="orderData.coupon_items.length > 0">
            <van-cell title="现金消费券" :value="coupon_deduction" is-link error>
                <template #icon>
                    <img class="youhui_icon" src="../../images/mine/youhui_icon.png" />
                </template>
</van-cell>
</div> -->
        <!--  @click="getCoupon" v-if="orderData.coupon_items.length>0"-->
        <!-- <div class="youhui_title" v-if="orderData.consume_gold > 0">
            <van-cell title="消费金" :value="'当前余额' + orderData.consume_gold" error
                :style="{ border: checked ? '.01rem solid rgba(243,42,35,0.6)' : '.01rem solid #fff', }">
                <template #icon>
                    <img class="youhui_icon" src="../../images/mine/youhui_icon.png" />
                </template>
                <template #right-icon>
                    <van-checkbox style="margin-left: .2rem;" v-model="checked" icon-size=".3rem"
                        checked-color="#60c60f" @change="handleChange"></van-checkbox>
                </template>
            </van-cell>
        </div> -->

        <!-- 现金券 -->
        <div v-if="cash_show > 0" class="cash-box" :class="{ 'cash-box-active': cashBoxChecked }" @click="toggleCashBox">
            <div class="cash-box-content">
                <div class="cash-img"><img src="../../images/mine/icon_cash.png" alt=""></div>
                <div class="cash-content">
                    <div>{{cash_deduction.title}}</div>
                    <div class="cash-content-desc">{{ cash_deduction.content }}</div>
                </div>
            </div>
            <img class="check-icon" :src="cashBoxChecked ? require('../../images/mine/xuanzhong.png') : require('../../images/mine/weixuanzhong.png')" alt="选中图标">
        </div>



        <!-- 底部 -->
        <div class="action-bottom">
            <div class="action-price">
                <div class="action-price-val">{{ orderData.summary_price || '0.00' }}</div>
                <div class="action-price-subsity" v-if="orderData.summary_gift_gxz > 0">赠贡献值：<span
                        class="action-price-subsity-red">{{ orderData.summary_gift_gxz || '' }}</span></div>
            </div>
            <div @click="handleToSave" class="action-btn active-btn">提交订单</div>
        </div>
        <!-- 地址 -->
        <van-popup v-model="showPopup" position="bottom">
            <van-cascader v-model="cascaderValue" title="请选择地址" :options="options" @close="showPopup = false"
                @change="onChange" @finish="onFinish" active-color="#31A653" />

        </van-popup>
    </div>
</template>

<script>
import { addressArrowIcon, addressBorderBg, addressLationIcon, orderShopIcon, goodCeilArrow } from '@/tool/static-img';
import { ADDRESS_DEFAULT, ORDER_CONFIRM, ORDER_SUBMIT, REGION_LIST } from '@/api/home';

import myLocation from './components/my-location';
// import { bannerToParams } from '@/tool/methods';
// import AMapLoader from '@amap/amap-jsapi-loader';
export default {
    components: {
        // myLocation,
    },
    data() {
        return {
            addressArrowIcon, addressBorderBg, addressLationIcon, goodCeilArrow,
            orderShopIcon,
            defaultAddress: null,
            orderData: null,
            isLoaded: false,
            btnLoad: false,
            coupon_deduction: "",
            cash_show: null, // 是否显示现金券抵扣
            cash_deduction: {}, // 现金券抵扣
            amt: '444',
            checked: false,
            cashBoxChecked: false,
            // 地址
            address: '',
            showPopup: false,
            cascaderValue: '',
            options: [],
            tabIndex: 0,
            code: ''
        }
    },
    async created() {
        const hasSelectAddress = localStorage.getItem('hasSelectAddress');
        if (hasSelectAddress) {
            this.isLoaded = true;
            this.defaultAddress = JSON.parse(hasSelectAddress);
        }
        // console.log(this.$route.query.coupon_id);
        // if(){
        //     this.youhui=
        // }
        localStorage.removeItem('coupon_items')

        // 确认订单
        this.confirmOrder(this.$route.query.coupon_id);
        this.fetchRegions(1, 0);
    },
    methods: {
        onClickLeft() {
            this.$router.back()
        },
        async fetchRegions(parentCode, level) {
            const res = await this.$http.get(REGION_LIST, {
                params: {
                    code: parentCode
                }
            })
            const {
                data
            } = res;

            // 省级
            if (level === 0) {
                data.forEach(item => {
                    this.options.push({
                        text: item.name,
                        value: item.code,
                        children: []
                    });
                })
            } else if (level === 1) {
                // 市级数据
                const province = this.options.find(item => item.value === parentCode);
                if (province) {
                    province.children = data.map(item => ({
                        text: item.name,
                        value: item.code,
                        children: []
                    }));
                }
            } else if (level === 2) {
                // 区/县级数据
                this.options.forEach(province => {
                    const city = province.children.find(item => item.value === parentCode);
                    if (city) {
                        city.children = data.map(item => ({
                            text: item.name,
                            value: item.code,
                            children: []
                        }));
                    }
                });
            }
        },
        // 选择器变化时的回调
        onChange(res) {
            this.tabIndex = res.tabIndex;
            if (this.tabIndex === 2) {
                return;
            }
            console.log(res, 'jj')
            //点击加载下一级回调
            this.getSpaceListAgain(res.selectedOptions, res.value);
        },
        getSpaceListAgain(selectedOptions, value) {
            this.$http.get(REGION_LIST, {
                params: {
                    code: value
                }
            })
                .then(res => {
                    const {
                        data
                    } = res;

                    if (data && data.length) {
                        this.setOptions(selectedOptions, data);
                    }
                })
        },
        setOptions(selectedOptions, data) {
            let _options = this.options;
            selectedOptions.forEach((item, index) => {
                if (index) {
                    //不是第一个则取下一级children
                    _options = _options.children;
                }
                _options = _options[_options.findIndex((_item) => _item.value === item.value)];
            });
            //找到最后一级
            _options.children = data.map((item) => {
                return {
                    text: item.name,
                    value: item.code,
                    children: this.tabIndex == 1 ? null : [],
                };
            });
        },
        onFinish({ selectedOptions }) {

            this.showPopup = false;

            this.selectAreaList = selectedOptions;

            selectedOptions = selectedOptions.filter(item => {

                return item.value !== 0;
            })

            console.log(selectedOptions, 'll')
            this.code = selectedOptions[selectedOptions.length - 1]?.value
            this.address = selectedOptions.map((option) => option.text).join('/');
        },
        // 选择地址
        handleToSelectAddress() {
            this.$router.push({
                name: 'address'
            })
        },
        handleChange() {
            this.confirmOrder(this.$route.query.coupon_id);
        },
        // 确认订单
        confirmOrder(coupon_id) {
            const orderItem = JSON.parse(localStorage.getItem('orderItem'));
            let params = {};
            params['address_id'] = !this.defaultAddress ? null : this.defaultAddress.id;
            if (!orderItem.from_cart) {
                params['from_cart'] = 0;
                params['goods_id'] = orderItem.goods_id;
                params['spec_id'] = orderItem.spec_id;
                params['quantity'] = orderItem.quantity;
                params['coupon_id'] = Number(coupon_id);
                // params['use_consume_gold'] = this.checked ? 1 : 0
                params['use_cash_coupon'] = this.cashBoxChecked ? 1 : 0
            } else {
                params['from_cart'] = 1;
                params['coupon_id'] = Number(coupon_id)
                // params['use_consume_gold'] = this.checked ? 1 : 0
                params['use_cash_coupon'] = this.cashBoxChecked ? 1 : 0

            }


            this.$http.post(ORDER_CONFIRM, params)
                .then(res => {
                    const {
                        data
                    } = res;

                    this.orderData = data;
                    this.coupon_deduction = data.coupon_deduction
                    this.cash_show = data.xjq_deduction_show // 是否显示现金券抵扣
                    this.cash_deduction = data.xjq_deduction_info // 现金券抵扣

                    localStorage.setItem('coupon_items', JSON.stringify(data.coupon_items));
                    if (coupon_id) {
                        // this.orderData.summary_price=this.orderData.summary_price-this.youhui
                    }
                })
                .finally(() => {
                    this.isLoaded = true;
                })
        },
        // 优惠券
        getCoupon() {
            this.$router.replace({
                path: '/coupon',
                query: {
                    coupon_id: this.$route.query.coupon_id,
                    goods: 1
                }
            })
        },
        // 切换现金券选中状态
        toggleCashBox() {
            this.cashBoxChecked = !this.cashBoxChecked;
            // 重新调用确认订单接口，更新价格和贡献值
            this.confirmOrder(this.$route.query.coupon_id);
        },
        // 订单
        handleToSave() {
            if (!this.orderData.address.address) {
                this.$toast('请先选择地址')
                return
            }
            if (this.orderData.belong_status == 1) {
                if (!this.code) {
                    this.$toast('请先选择归属区域')
                    return
                }
            }


            const orderItem = JSON.parse(localStorage.getItem('orderItem'));

            let params = {};
            params['address_id'] = this.orderData.address.id;
            params['belong_code'] = this.code
            if (!orderItem.from_cart) {
                params['from_cart'] = 0;
                params['goods_id'] = orderItem.goods_id;
                params['spec_id'] = orderItem.spec_id;
                params['quantity'] = orderItem.quantity;
                params['coupon_id'] = Number(this.$route.query.coupon_id)
                // params['use_consume_gold'] = this.checked ? 1 : 0
                params['use_cash_coupon'] = this.cashBoxChecked ? 1 : 0

            } else {
                params['from_cart'] = 1;
                params['coupon_id'] = Number(this.$route.query.coupon_id)
                // params['use_consume_gold'] = this.checked ? 1 : 0
                params['use_cash_coupon'] = this.cashBoxChecked ? 1 : 0
            }

            params['notes'] = this.orderData.items.map(item => {
                return {
                    shop_id: item.shop_id,
                    user_note: item.user_note
                }
            })

            if (this.btnLoad) {
                return
            }
            this.btnLoad = true;
            this.$http.post(ORDER_SUBMIT, params)
                .then((res) => {
                    localStorage.removeItem('hasSelectAddress');
                    localStorage.removeItem('orderItem');
                    // 截止时间
                    res.data.expired_time = new Date().getTime() + res.data.expired_seconds * 1000;
                    localStorage.setItem('cashOrder', JSON.stringify(res.data))

                    // 去收银台
                    this.$router.replace({
                        name: 'cashier'
                    })
                })
                .catch(() => {
                    // this.isLoaded = false;
                })

        }
    }
}

</script>
<style lang="scss" scoped>
.order-wrap {
    position: relative;
    min-height: 100vh;
    padding-top: 46px;
    background-color: #f4f4f4;
    padding-bottom: calc(1.2rem + constant(safe-area-inset-bottom));
    padding-bottom: calc(1.2rem + env(safe-area-inset-bottom));
    box-sizing: border-box;

    ::v-deep .van-nav-bar .van-icon {
        color: #333333;
    }

    ::v-deep .van-nav-bar__arrow {
        font-size: 20px;
    }

    ::v-deep .van-hairline--bottom::after {
        display: none;
    }

    ::v-deep .van-field__control {
        text-align: right;
    }

    .cash-box {
        box-sizing: border-box;
        margin: 0.3rem 0.24rem;
        display: flex;
        align-items: center;
        justify-content: space-between;
        height: 1.28rem;
        padding: 0.24rem 0.32rem;
        background-color: #ffffff;
        border-radius: 0.12rem;
        border: 0.01rem solid transparent;
        transition: border-color 0.3s;
        
        &.cash-box-active {
            border-color: #62B457;
        }

        .cash-box-content {
            display: flex;
            align-items: center;
            justify-content: flex-start;

            .cash-img {
                width: 0.6rem;
                height: 0.6rem;

                img {
                    width: 0.6rem;
                    height: 0.6rem;
                }
            }

            .cash-content {
                margin-left: 0.28rem;
                font-weight: 400;
                font-size: .28rem;
                color: #333333;
                line-height: 0.4rem;

                .cash-content-desc {
                    margin-top: 0.08rem;
                    font-size: 0.24rem;
                    color: #F32A23;
                    line-height: 0.32rem;
                }
            }
        }

        .check-icon {
            width: 0.32rem;
            height: 0.32rem;
            display: block;
            object-fit: contain;
            visibility: visible;
            opacity: 1;
        }


    }

 

    .action-bottom {
        display: flex;
        justify-content: space-between;
        position: fixed;
        bottom: 0;
        left: 0;
        height: 1.08rem;
        width: 100%;

        padding-bottom: constant(safe-area-inset-bottom);
        padding-bottom: env(safe-area-inset-bottom);
        background: #ffffff;

        .action-price {
            display: flex;
            flex-direction: column;
            justify-content: center;
            // align-items: center;
            margin-left: 0.32rem;

            // text-align: right;
            .action-price-val {
                display: flex;
                align-items: center;

                span {
                    font-size: .24rem;
                    color: #333;
                }

                height: 0.56rem;
                // margin-bottom: 0.04rem;
                line-height: 0.56rem;
                font-size: 0.32rem;
                font-weight: 500;
                color: #F32A23;
                margin-right: .2rem;
                // &::before{
                //     content: '¥';
                //     font-size: 0.24rem;
                // }
            }

            .action-price-subsity {
                height: 0.34rem;
                line-height: 0.34rem;
                font-size: 0.24rem;
                font-weight: 400;
                color: #333333;

                .action-price-subsity-red {
                    color: rgba(49, 166, 83, 1);
                }
            }
        }

        .action-btn {
            display: flex;
            align-items: center;
            justify-content: center;
            width: 2.04rem;
            height: 0.8rem;
            margin-top: 0.14rem;
            margin-right: 0.32rem;
            font-size: 0.28rem;
            font-weight: 500;
            color: #ffffff;

            border-radius: 0.4rem;
            background: linear-gradient(90deg, #75BE70 0%, #56AE48 100%);
        }
    }

    .address-top-box {
        min-height: 1.76rem;
        width: 100%;
        background: #ffffff;
    }

    .no-address-box {
        position: relative;
        display: flex;
        align-items: center;
        justify-content: space-between;
        height: 1.76rem;
        margin-bottom: 0.16rem;
        background-color: #ffffff;

        .address-border-bottom {
            position: absolute;
            bottom: 0;
            left: 0;
            width: 100%;
            height: 0.04rem;
        }

        .address-default-text {
            height: 0.44rem;
            margin-left: 0.32rem;
            line-height: 0.44rem;
            font-weight: 500;
            font-size: 0.32rem;
            color: #333333;
        }

        .address-arrow-icon {
            width: 0.32rem;
            height: 0.32rem;
            margin-right: 0.32rem;
        }
    }

    .default-box {
        position: relative;
        display: flex;
        align-items: center;
        padding: 0.4rem 0.32rem;
        box-sizing: border-box;
        background: #ffffff;

        .address-border-bottom {
            position: absolute;
            bottom: 0;
            left: 0;
            width: 100%;
            height: 0.04rem;
        }

        .address-lation {
            width: 0.4rem;
            height: 0.4rem;
            margin-right: 0.24rem;
        }

        .address-arrow-icon {
            width: 0.32rem;
            height: 0.32rem;
            margin-right: 0.32rem;
        }

        .address-content {
            flex-shrink: 0;
            width: 5.5rem;
            margin-right: 0.4rem;

            .address-content-name {
                display: flex;
                align-items: center;
                margin-bottom: 0.12rem;

                .address-user-name {
                    height: 0.44rem;
                    margin-right: 0.16rem;
                    line-height: 0.44rem;
                    font-weight: 500;
                    font-size: 0.32rem;
                    color: #333333;
                }

                .address-user-tel {
                    font-size: 0.28rem;
                    font-weight: 400;
                    color: #999999;
                }
            }

            .address-content-info {
                line-height: 0.4rem;
                font-size: 0.28rem;
                font-weight: 400;
                color: #999999;
            }
        }
    }

    .good-shop-box {
        padding: 0.32rem;
        margin-bottom: 0.16rem;
        background: #ffffff;

        .shop-top {
            display: flex;
            align-items: center;
            margin-bottom: 0.24rem;

            .shop-top-icon {
                width: 0.4rem;
                height: 0.4rem;
                margin-right: 0.16rem;
            }

            .shop-top-title {
                font-weight: 500;
                font-size: 0.28rem;
                color: #333333;
            }
        }

        .good-item {
            position: relative;
            display: flex;
            margin-bottom: 0.42rem;

            .good-num-fix {
                position: absolute;
                right: 0;
                bottom: 0;
                font-weight: 400;
                font-size: 0.26rem;
                color: #999999;
            }

            .good-item-img {
                width: 1.8rem;
                height: 1.8rem;
                border-radius: 0.16rem;
            }

            .good-item-content {
                width: 4.5rem;
                height: 0.4rem;
                margin-left: 0.24rem;

                .good-item-content-name {
                    margin-bottom: 0.04rem;
                    line-height: 0.4rem;
                    font-weight: 500;
                    font-size: 0.28rem;
                    color: #333333;
                    white-space: nowrap;
                    overflow: hidden;
                    text-overflow: ellipsis;
                    word-break: break-all;
                }

                .good-item-content-sku {
                    height: 0.34rem;
                    margin-bottom: 0.12rem;
                    line-height: 0.34rem;
                    font-weight: 400;
                    font-size: 0.24rem;
                    color: #999999;
                    white-space: nowrap;
                    overflow: hidden;
                    text-overflow: ellipsis;
                    word-break: break-all;
                }

                .good-info-subsidy {
                    // display: flex;
                    // height: 0.36rem;
                    margin-top: 0.08rem;
                    display: inline-block;
                    padding: 0 0.12rem;
                    border-radius: .06rem;
                    border: 1px solid #31A653;

                    .good-info-subsidy-btn {
                        background: transparent;
                        // width: 45%;
                        display: flex;
                        // margin-right: .3rem;
                        color: #FF6200;
                        // opacity: 0.07;
                        background-size: cover;
                        align-items: center;
                        // justify-content: center;
                        height: 0.36rem;
                        // padding: 0 0.12rem;
                        font-weight: 400;
                        font-size: 0.22rem;
                        border-radius: 0.06rem;
                        // text-indent: .1rem;
                        box-sizing: border-box;
                    }

                    .hd_bt {
                        // background: #fdf4ee;
                        color: #FF6200;
                        margin-bottom: .05rem;
                    }
                }

                .good-item-price {
                    height: 0.44rem;
                    line-height: 0.44rem;
                    font-size: 0.32rem;
                    font-weight: 500;
                    margin-bottom: 0.15rem;
                    margin-top: .1rem;
                    color: #F32A23;
                }
            }
        }
    }

    .good-remark {
        border-radius: 0.16rem;
        overflow: hidden;
        background: #F4F4F4;

        .van-cell {

            background: #f4f4f4;

            .van-field__label {
                width: 1.36rem;
                margin-right: 0;
                color: #333333;
            }
        }
    }

    .good-total {
        display: flex;
        justify-content: flex-end;
        align-items: center;
        line-height: 0.5rem;
        margin-top: 0.32rem;

        .good-total-num {
            font-size: 0.24rem;
            color: #999999;
        }

        .good-total-price {
            font-weight: 500;
            font-size: 0.36rem;
            color: rgba(49, 166, 83, 1);
        }
    }


}

.youhui_title {
    margin: .2rem;

    .van-cell {
        border-radius: .1rem;
        border: .01rem solid #ffffff;
    }

    .van-cell__value {
        color: #FF6200;
    }

    .youhui_icon {
        width: .6rem;
        vertical-align: middle;
        margin-top: -.1rem;
        margin-right: .2rem;
    }
}
</style>